const path = window.location.host
const WSS_URL = 'ws://' + path + '/ws/chat/'
const TEST_URL = 'ws://127.0.0.1:8000/ws/chat/123/'
let Socket = ''
let setIntervalWebsocketPush = null

/** 建立连接 */
export function createSocket(projectId) {
    if (!Socket) {
        console.log('建立websocket连接')
        Socket = new WebSocket(WSS_URL + projectId)
        Socket.onopen = onopenWS
        Socket.onmessage = onmessageWS
        Socket.onerror = onerrorWS
        Socket.onclose = oncloseWS
    } else {
        console.log('websocket已连接')
    }
}
export function testCreate() {
    if (!Socket) {
        console.log('建立websocket连接')
        Socket = new WebSocket(TEST_URL)
        //      Socket.onopen = onopenWS
        Socket.onmessage = onmessageWS
        Socket.onerror = onerrorWS
        Socket.onclose = oncloseWS
    } else {
        console.log('websocket已连接')
    }
}


/** 打开WS之后发送心跳 */
export function onopenWS() {
    sendPing() // 发送心跳
}
/** 连接失败重连 */
export function onerrorWS() {
    clearInterval(setIntervalWebsocketPush)
    Socket.close()
    createSocket() // 重连
}
/** WS数据接收统一处理 */
export function onmessageWS(e) {
    window.dispatchEvent(new CustomEvent('onmessageWS', {
        detail: e.data,
    }))
}
/** 发送数据 */
export function sendWSPush(eventTypeArr) {
    const obj = {
        appId: 'airShip',
        cover: 0,
        event: eventTypeArr,
    }
    if (Socket !== null && Socket.readyState === 3) {
        Socket.close()
        createSocket() // 重连
    } else if (Socket.readyState === 1) {
        Socket.send(JSON.stringify(obj))
    } else if (Socket.readyState === 0) {
        setTimeout(() => {
            Socket.send(JSON.stringify(obj))
        }, 3000)
    }
}
/** 关闭WS */
export function oncloseWS() {
    clearInterval(setIntervalWebsocketPush) // 取消由setInterval()设置的timeout。
    Socket = ''
    console.log('websocket已断开')
}
/** 发送心跳 */
export function sendPing() {
    Socket.send('ping')
    setIntervalWebsocketPush = setInterval(() => {
        Socket.send('ping')
    }, 5000)
}
